import { Injectable } from '@nestjs/common';
import { and, asc, eq, ilike } from 'drizzle-orm';
import { BaseService, sysDictData, type SysDictData } from '@nbase/db';
import type { IDictData, IPaginationResponse } from '@nbase/shared';
import { CreateDictDataDto } from './dto/create-dict-data.dto';
import { UpdateDictDataDto } from './dto/update-dict-data.dto';
import { QueryDictDataDto } from './dto/query-dict-data.dto';
import { toDictData, toDictDataPage } from './dict-data.mapper';

/**
 * 字典数据服务
 */
@Injectable()
export class DictDataService extends BaseService<typeof sysDictData> {
  constructor() {
    super(sysDictData);
  }

  /**
   * 创建字典数据
   */
  async createDictData(createDictDataDto: CreateDictDataDto): Promise<IDictData> {
    const created = await this.create(createDictDataDto);
    return toDictData(created as SysDictData);
  }

  /**
   * 更新字典数据
   */
  async updateDictData(id: string, updateDictDataDto: UpdateDictDataDto): Promise<IDictData> {
    const updated = await this.update(id, updateDictDataDto);
    return toDictData(updated as SysDictData);
  }

  /**
   * 删除字典数据
   */
  async deleteDictData(id: string): Promise<void> {
    await this.softDelete(id);
  }

  /**
   * 分页查询字典数据
   */
  async paginateDictData(query: QueryDictDataDto): Promise<IPaginationResponse<IDictData>> {
    const conditions = [];

    // 根据字典 ID 筛选
    if (query.dictId) {
      conditions.push(eq(sysDictData.dictId, query.dictId));
    }
    if (query.label) {
      conditions.push(ilike(sysDictData.label, `%${query.label}%`));
    }
    if (query.value) {
      conditions.push(eq(sysDictData.value, query.value));
    }
    if (query.status !== undefined) {
      conditions.push(eq(sysDictData.status, query.status));
    }

    const where = conditions.length > 0 ? and(...conditions) : undefined;

    const result = await this.paginate(query, where);
    return toDictDataPage(result as IPaginationResponse<SysDictData>);
  }

  /**
   * 根据字典 ID 获取所有字典数据
   */
  async findByDictId(dictId: string): Promise<IDictData[]> {
    const list = await this.find(eq(sysDictData.dictId, dictId), {
      orderBy: asc(sysDictData.sort),
    });
    return (list as SysDictData[]).map(toDictData);
  }

  /**
   * 根据字典 ID 和值查找
   */
  async findByDictIdAndValue(dictId: string, value: string): Promise<IDictData | null> {
    const data = (await this.findOne(
      and(eq(sysDictData.dictId, dictId), eq(sysDictData.value, value))!
    )) as SysDictData | undefined;
    return data ? toDictData(data) : null;
  }
}

